package com.admin.education.services.Implements;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.common.exceptions.ResourceNotFoundException;
import com.admin.education.dataTransferObject.PageResponse;
import com.admin.education.dataTransferObject.ServicesExcuteResult;
import com.admin.education.dataTransferObject.question.Mapper.QuestionMapper;
import com.admin.education.dataTransferObject.question.QuestionTransfer;
import com.admin.education.dataTransferObject.question.Request.CreateQuestionRequest;
import com.admin.education.dataTransferObject.question.Request.QueryQuestionRequest;
import com.admin.education.dataTransferObject.question.Request.UpdateQuestionRequest;
import com.admin.education.models.*;
import com.admin.education.repositories.AnswerRepository;
import com.admin.education.repositories.QuestionRepository;
import com.admin.education.repositories.SubjectsRepository;
import com.admin.education.services.Interfaces.IQuestionService;
import com.querydsl.jpa.impl.JPAQuery;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.List;

@Service
@Validated
@Transactional
public class QuestionService implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRepository questionRepository;
    private QQuestions qQuestions;
    private QSubjects qSubjects;
    private QAnswers qAnswers;
    @Autowired
    private AnswerRepository answerRepository;
    @Autowired
    private SubjectsRepository subjectsRepository;
    public QuestionService(){
        qQuestions = QQuestions.questions;
        qSubjects =QSubjects.subjects;
        qAnswers = QAnswers.answers;
    }
    @Override
    public ServicesExcuteResult<PageResponse<QuestionTransfer>> queryQuestions(@Valid QueryQuestionRequest queryQuestionRequest) {
        ServicesExcuteResult<PageResponse<QuestionTransfer>> servicesExcuteResult= new ServicesExcuteResult<>();

        JPAQuery<Questions> questionsJPAQuery = this.questionRepository.selectFrom(qQuestions);
        if(!StringUtils.isEmpty(queryQuestionRequest.getName())){
            questionsJPAQuery = questionsJPAQuery.where(qQuestions.examinationQuestions.eq(queryQuestionRequest.getName()));
        }
        if(null!=queryQuestionRequest.getSubjectId()){
            questionsJPAQuery = questionsJPAQuery.where(qQuestions.subjects.id.eq(queryQuestionRequest.getSubjectId()));
        }
        if(null!=queryQuestionRequest.getQuestionType()){
            questionsJPAQuery = questionsJPAQuery.where(qQuestions.questionType.eq(queryQuestionRequest.getQuestionType()));
        }
        long totalCount= questionsJPAQuery.fetchCount();

        questionsJPAQuery = questionsJPAQuery.orderBy(qQuestions.id.asc())
                                                .offset(queryQuestionRequest.getPageSize()*(queryQuestionRequest.getPageIndex()-1)).limit(queryQuestionRequest.getPageSize());

        List<Questions> questions = questionsJPAQuery.fetch();

        List<QuestionTransfer> questionTransfers = questionMapper.mapFrom(questions);

        PageResponse<QuestionTransfer> questionTransferPageResponse = new PageResponse<>(queryQuestionRequest.getPageSize(),queryQuestionRequest.getPageIndex(),(int)totalCount,questionTransfers);

        servicesExcuteResult.setData(questionTransferPageResponse);
        servicesExcuteResult.setSuccess(true);
        return servicesExcuteResult;
    }

    @Override
    public ServicesExcuteResult createQuestion(@Valid CreateQuestionRequest createQuestionRequest) throws BadRequestException {
        ServicesExcuteResult servicesExcuteResult = new ServicesExcuteResult();

        JPAQuery<Subjects> subjectsJPAQuery = this.subjectsRepository.selectFrom(qSubjects).where(qSubjects.id.eq(createQuestionRequest.getSubjectId()));
        if(0==subjectsJPAQuery.fetchCount()){
            servicesExcuteResult.setErrorMessage("不存在这科目");
            return servicesExcuteResult;
        }

        Subjects subjects = subjectsJPAQuery.fetchFirst();

        Questions questions = questionMapper.mapFrom(createQuestionRequest);
        questions.setSubjects(subjects);

        this.questionRepository.persist(questions);
        this.answerRepository.persist(questions.getAnsweres());

        servicesExcuteResult.setSuccess(true);
        return servicesExcuteResult;
    }

    @Override
    public ServicesExcuteResult deleteQuestion(long questionId) throws ResourceNotFoundException {
        ServicesExcuteResult servicesExcuteResult = new ServicesExcuteResult();

        JPAQuery<Questions> questionJPAQuery = this.questionRepository.selectFrom(qQuestions).where(qQuestions.id.eq(questionId));

        if(0!=questionJPAQuery.fetchCount()){
            List<Answers> answers = this.answerRepository.selectFrom(qAnswers).where(qAnswers.questions.id.eq(questionId)).fetch();

            for (Answers answer : answers) {
                this.answerRepository.remove(answer);
            }
            this.questionRepository.remove(questionJPAQuery.fetchFirst());

            servicesExcuteResult.setSuccess(true);
        }
        else{
            throw new ResourceNotFoundException("问题不存在");
        }
        return servicesExcuteResult;
    }

    @Override
    public ServicesExcuteResult updateQuestion(long questionId, @Valid UpdateQuestionRequest updateQuestionRequest) throws BadRequestException, ResourceNotFoundException {
        ServicesExcuteResult servicesExcuteResult = new ServicesExcuteResult();

        JPAQuery<Questions> questionJPAQuery = this.questionRepository.selectFrom(qQuestions).where(qQuestions.id.eq(questionId));

        if(0!=questionJPAQuery.fetchCount()){

            Questions questions = questionMapper.mapFrom(updateQuestionRequest,questionJPAQuery.fetchFirst());

            List<Answers> answers = this.answerRepository.selectFrom(qAnswers).where(qAnswers.questions.id.eq(questionId)).fetch();

            for (Answers answer : answers) {
                this.answerRepository.remove(answer);
            }
            this.questionRepository.persist(questions);
            this.answerRepository.persist(questions.getAnsweres());

            servicesExcuteResult.setSuccess(true);
        }
        else{
            throw new ResourceNotFoundException("问题不存在");
        }
        return servicesExcuteResult;
    }

    @Override
    public ServicesExcuteResult<QuestionTransfer> queryQuestionById(long questionId) throws ResourceNotFoundException {
        ServicesExcuteResult servicesExcuteResult = new ServicesExcuteResult();

        JPAQuery<Questions> questionJPAQuery = this.questionRepository.selectFrom(qQuestions).where(qQuestions.id.eq(questionId));

        if(0!=questionJPAQuery.fetchCount()) {
            Questions questions = questionJPAQuery.fetchFirst();

            servicesExcuteResult.setSuccess(true);
            servicesExcuteResult.setData(questionMapper.mapFrom(questions));
        }
        else{
            throw new ResourceNotFoundException("问题不存在");
        }
        return servicesExcuteResult;
    }
}
